Select Sort

#C#

Posted by Phyxsius on 2023-09-26


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = new int[5];    //宣告陣列大小為10

        Random rnd = new Random();  //產生亂數初始值

        for (int i=0; i<ary.Length; i++)
        {
            ary[i] = rnd.Next(1, 10);   //亂數產生,亂數產生的範圍是1~9
        }

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        SelectSort(ary);

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    static void SelectSort(int[] ary)
    {
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();  //計算程式時間開始

        int counter = 0;
        int min;
        int minIndex = 0;  //陣列位址

        for (int i = 0; i < ary.Length; i++)
        {
            min = ary[i];   //此迴圈初始值設為最小值
            minIndex = i;   //位址預設為i(自己)

            for (int j = i+1; j < ary.Length; j++)
            {
                if (ary[j] < min)
                {
                    min = ary[j];
                    minIndex = j;
                }
                counter++;
            }

            //最小值是自己,不需要交換
            if(minIndex != i)
            {
                swap(ary, i, minIndex);
            }
            Console.Write($"第{i + 1}輪結果:");
            showArray(ary);
        }

        Console.WriteLine("執行次數:" + counter);

        stopWatch.Stop();   //計算程式時間結束
        Console.WriteLine("程式執行時間(秒):" + (stopWatch.Elapsed.TotalMilliseconds/1000));
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

test

test

#Tailwind #Webpack resolve-url-loader cannot operate: CSS error

#Tailwind #Webpack resolve-url-loader cannot operate: CSS error

響應式網站製作重點

響應式網站製作重點


Comments